var util = require('../utils/util');
var daoUtil = require('../utils/daoUtil');
var stock_history_priceClass = require('../class/stock_history_price');

module.exports = {

    create: function (params, cb) {
        var validate = daoUtil.validate(['price', 'stockId', 'date'], params);
        if (!validate.valid) {
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function (models) {
            var stock_history_price = new stock_history_priceClass();
            stock_history_price.init(params);
            models.stock_history_price.findOrCreate(stock_history_price.getParams(), function (err, data) {
                if (err || !data) {
                    console.error(err);
                    cb(util.getSysError());
                } else {
                    data.createAt = util.dateFormat(data.createAt);
                    cb(null, util.getSuccessRes(data));
                }
            });
        }, cb);
    },
    //获取股票指定时间上一天收盘价
    getListPriceByTime: function (params, cb) {
        var validate = daoUtil.validate(['date', 'stockCodes'], params);
        if (!validate.valid) {
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function (models) {
            var sql = "select price,stockId stockCode,date from tb_stock_history_price a ,(select max(date)da from tb_stock_history_price  where  date <'" + params.date + "' ) b";
            sql += " where a.date = b.da ";
            var i = 0;
            if(params.stockCodes && params.stockCodes.length >0 ){
                sql += 'and stockId in ( ';
                for (stockCode of params.stockCodes) {
                    sql += "'" + stockCode + "'";
                    if (i < params.stockCodes.length - 1)
                        sql += ",";
                    i++;
                }
                sql += " ) order by stockCode";
            }

            models.stock_history_price.query(sql, function (err, data) {
                if (err || !data) {
                    console.error(err);
                    cb(util.getSysError());
                } else {
                    cb(null, util.getSuccessRes(data));
                }
            });
        }, cb);
    },
    //获取股票周期内收盘价
    getListPriceInTimes: function (params, cb) {
        var validate = daoUtil.validate(['startDate','endDate', 'stockCodes'], params);
        if (!validate.valid) {
            cb(validate.error);
            return;
        }
        daoUtil.proxy(function (models) {
            models.stock_history_price.find({stockId:params.stockCodes,date:{'>':params.startDate,'<':params.endDate}}, function (err, data) {
                if (err || !data) {
                    console.error(err);
                    cb(util.getSysError());
                } else {
                    cb(null, util.getSuccessRes(data));
                }
            });
        }, cb);
    }

};